<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" size="small"  v-model="queryInfo.name" class="input-with-select" clearable @clear="getRoleList">
            <el-button slot="append" icon="el-icon-search" @click="getRoleList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" v-has="'dashboard/save_role'"  @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe  v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1===0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.child"
                    :key="item1.id">
              <!--渲染一级菜单 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row,item1.id)">{{item1.title}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级菜单 -->
              <el-col :span="19">
                <el-row :class="[i2===0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.child" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRoleById(scope.row,item2.id)">{{item2.title}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" closable @close="removeRoleById(scope.row,item3.id)"
                            v-for="(item3,i3) in item2.child" :key="item3.id">{{item3.title}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="title" label="角色名称"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
                       :active-value="1"
                       v-has="'dashboard/update_role_status'"
                       :inactive-value="0"
                       @change="changeStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" v-has="'dashboard/save_role'" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)" size="mini"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" v-has="'dashboard/del_role'" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini"
                         @click="showDelDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配权限" v-has="'dashboard/set_role_user_pivot'" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                         @click="showSetRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClose">
      <el-form :model="addRoleForm" :rules="addRoleFormRule" ref="addRoleFormRef" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="角色名称" prop="title">
          <el-input v-model="addRoleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addRoleForm.status"
                     :active-value="1"
                     :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改角色" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleDialogClose">
      <el-form :model="editRoleForm" :rules="editRoleFormRule" ref="editRoleFormRef" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="角色名称" prop="title">
          <el-input v-model="editRoleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="editRoleForm.status"
                     :active-value="1"
                     :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="showSetRoleDialogVisible"
      width="50%" @close="showSetRoleDialogClose">
      <el-tree :data="rightList" :props="defaultProps" show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showSetRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        name:'',
        limit: this.$global_limit,
        page: this.$global_page
      },
      loading:true,
      roleList: [],
      total: 0,
      //所有权限的数据
      rightList: [],
      editRoleDialogVisible: false,
      showSetRoleDialogVisible: false,
      addRoleForm: {
        title: '',
        rules: '',
        status: 1
      },
      editRoleForm: {
        title: '',
        status: 1
      },
      defaultKeys: [],
      defaultProps: {
        children: 'child',
        label: 'title'
      },
      editRoleFormRule: {
        title: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
      },
      addRoleFormRule: {
        title: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
      },
      id: '',
      title: '',
      status: '',
      treeType: 'child',
      addRoleDialogVisible: false
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const {data: res} = await this.$http.get('dashboard/role_list', {params: this.queryInfo})
      if (res.code !== 200) return this.$message.error(res.data.message)
      this.roleList = res.data.list
      this.total = res.data.totalCount
      this.loading = false
    },
    handleSizeChange(newSize) {
      this.queryInfo.limit = newSize
      this.getRoleList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getRoleList()
    },
    editRoleDialogClose() {
      this.$refs.editRoleFormRef.resetFields()
    },
    addRoleDialogClose() {
      this.$refs.addRoleFormRef.resetFields()
    },
    showSetRoleDialogClose() {
      this.defaultKeys = []
    },
    //更改角色状态
    async changeStatus(roleList) {
      const {data: res} = await this.$http.put(`dashboard/update_role_status/${roleList.id}/${roleList.status}`)
      if (res.code !== 200) {
        roleList.status = 0
        return this.$message.error(res.data.message)
      }
      this.$message.success('更改成功')
      // this.getRoleList()
    },
    //根据id删除对应的权限
    async removeRoleById(role, role_id) {
      const configResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (configResult !== 'confirm') return this.$message.info('已取消删除')
      const {data: result} = await this.$http.delete(`dashboard/del_role/${role.id}/${role_id}`)
      if (result.code !== 200) return this.$message.error(result.data.message)
      this.$message.success('删除成功')

      role.child = result.data.list

    },
    async showDelDialog(id) {
      const configResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (configResult !== 'confirm') return this.$message.info('已取消删除')
      const {data: result} = await this.$http.delete(`dashboard/del_group/${id}`)
      if (result.code !== 200) return this.$message.error(result.data.message)
      //删除成功后页码改变返还为上一页
      let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
      let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
      this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;
      this.$message.success('删除成功')

      this.getRoleList()
    },
    showEditDialog(role) {
      if (role.id === 1) return this.$message.error('无法编辑超级管理员')
      this.editRoleForm.title = role.title
      this.editRoleForm.status = role.status
      this.$set(this.editRoleForm, 'id', role.id)
      this.$set(this.editRoleForm, 'rules', role.rules)
      this.editRoleDialogVisible = true;
    },
    editRoleInfo() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/save_role', this.editRoleForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('编辑角色成功')
        this.editRoleDialogVisible = false
        this.getRoleList()
      })
    },
    //分配权限
    async showSetRoleDialog(role) {
      if (role.id === 1) return this.$message.error('超级管理员不用分配')
      this.id = role.id
      this.title = role.title
      this.status = role.status
      //获取所有权限列表
      const {data: result} = await this.$http.get('dashboard/menu_list', {params: {'type':this.treeType}})
      if (result.code !== 200) return this.$message.error(result.data.message)
      this.rightList = result.data.list;
      this.getLeafKeys(role, this.defaultKeys)
      this.showSetRoleDialogVisible = true
    },
    getLeafKeys(node, arr) {
      if (!node.child) {
        return arr.push(node.id)
      }
      node.child.forEach(item => this.getLeafKeys(item, arr))
    },
    //保存权限
    async allotRights() {
      const keys = [
        //通过展开运算符...
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')
      const {data: result} = await this.$http.post('dashboard/save_role', {
        'id': this.id,
        'title': this.title,
        'status': this.status,
        'rules': idStr

      })
      if(result.code !== 200) return this.$message.error(result.data.message)
      this.$message.success('分配权限成功')
      this.showSetRoleDialogVisible = false
      this.getRoleList()
    },
    //新增角色
    addRoleInfo() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/save_role', this.addRoleForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('新增角色成功')
        this.addRoleDialogVisible = false
        this.getRoleList()
      })
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
